Silly Trick: Split a String into Lines

Shlomi Fish on 2007-06-06T16:19:01

Wow! I have a lot to blog about Perl here, so let's start. First of all, a really trivial trick that I wondered about and that avar on Freenode taught me (thanks!): how to split a string into lines while preserving the trailing "\n". It's very simple: my @a = split(/^/, $text). One thing I wonder is why I don't get an empty line at the beginning of the string, because:

perl -le 'my @a=split(/p/,"pillow pillow on the pall");print join(",",@a)'

Gives me an empty string as the first argument. I also wonder if using split(/^/, $text, -1) instead, will do any difference.


from the docs

stu42j on 2007-06-07T20:15:05

Empty leading (or trailing) fields are produced when there are positive width matches at the beginning (or end) of the string; a zero-width match at the beginning (or end) of the string does not produce an empty field.

Re:from the docs

Shlomi Fish on 2007-06-08T18:15:39

Thanks!